package com.ycl.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.common.Result;
import com.ycl.entity.Employee;
import com.ycl.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        // 将页面提交的密码password进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 根据用户提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        // 如果没有查询到用户则返回登录失败
        if (emp == null)
            return Result.error("用户名错误");

        // 密码比对，如果不一致则返回登录失败
        if (!emp.getPassword().equals(password))
            return Result.error("密码错误");

        // 查看员工状态，如果为已禁用，这返回员工账号已禁用
        if (emp.getStatus() == 0)
            return Result.error("账号已禁用");

        // 登录成功，将员工id存入Session并返回登录结果
        request.getSession().setAttribute("employee",emp.getId());
        return Result.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        // 清理Session中存储的当前登录员工的ID
        request.getSession().removeAttribute("employee");
        return Result.success("退出成功");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request,@RequestBody Employee employee){

        // 新增前查询员工是否已存在 -》（已用异常捕获拦截异常处理 com/ycl/common/GlobalExceptionHandle.java）
//        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Employee::getUsername,employee.getUsername());
//        Employee emp = employeeService.getOne(lqw);
//        if (emp != null)
//            return Result.error("用户已存在");

        log.info("新增员工，员工信息{}",employee.toString());
        // 设置初始密码123456并进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        // MybatisPlus自动字段填充 com/ycl/common/MyMetaObjectHandler.java
//        // 设置创建更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        // 获得当前登录用户ID
//        Long loginUserId = (Long) request.getSession().getAttribute("employee");
//        // 设置创建更新用户ID
//        employee.setCreateUser(loginUserId);
//        employee.setUpdateUser(loginUserId);
        employeeService.save(employee);
        return Result.success("新增员工成功");
    }

    /**
     * 分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Employee>> page(int page,int pageSize,String name){
        log.info("分页查询");
        // 构造分页构造器
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        // 构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName,name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        // 执行查询
        employeeService.page(pageInfo,queryWrapper);

        return Result.success(pageInfo);
    }

    /**
     * 修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());

        Long empId = (Long) request.getSession().getAttribute("employee");
        // MybatisPlus自动字段填充 com/ycl/common/MyMetaObjectHandler.java
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
        employeeService.updateById(employee);
        return Result.success("员工信息修改成功");
    }

    /**
     * 根据ID查询数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id){
        log.info("根据Id查询员工信息");
        Employee employee = employeeService.getById(id);
        return employee!=null?Result.success(employee):Result.error("没有此员工信息");
    }
}
